package com.wjc.network.errorhandler

import android.net.ParseException
import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import javax.net.ssl.SSLHandshakeException

/**
 * ClassName: com.wjc.network.errorhandler
 * Description:
 * JcChen on 2021.04.17.15:47
 */
object ExceptionHandle {

    private const val UNAUTHORIZED = 401
    private const val FORBIDDEN = 403
    private const val NOT_FOUND = 404
    private const val REQUEST_TIMEOUT = 408
    private const val INTERNAL_SERVER_ERROR = 500
    private const val BAD_GATEWAY = 502
    private const val SERVICE_UNAVAILABLE = 503
    private const val GATEWAY_TIMEOUT = 504

    /**
     * 未知错误
     */
    private const val UNKNOWN = 1000

    /**
     * 解析错误
     */
    private const val PARSE_ERROR = 1001

    /**
     * 网络错误
     */
    private const val NETWORD_ERROR = 1002

    /**
     * 协议出错
     */
    private const val HTTP_ERROR = 1003

    /**
     * 证书出错
     */
    private const val SSL_ERROR = 1005

    /**
     * 连接超时
     */
    private const val TIMEOUT_ERROR = 1006

    /**
     * RuntimeException
     */
    private const val RUNTIME_EXCEPTION = 1007

    fun handleException(e: Throwable) = when (e) {
        is HttpException -> {
            when (e.code()) {
                UNAUTHORIZED, FORBIDDEN, NOT_FOUND, REQUEST_TIMEOUT, GATEWAY_TIMEOUT,
                INTERNAL_SERVER_ERROR, BAD_GATEWAY, SERVICE_UNAVAILABLE -> ResponseThrowable(
                    e,
                    HTTP_ERROR,
                    "网络错误"
                )
                else -> ResponseThrowable(
                    e,
                    e.code(),
                    "HttpException"
                )
            }
        }
        is RuntimeException -> ResponseThrowable(e, RUNTIME_EXCEPTION, e.message)
        is JsonParseException, is JSONException, is ParseException -> ResponseThrowable(
            e,
            PARSE_ERROR,
            "解析错误"
        )
        is ConnectException -> ResponseThrowable(
            e,
            NETWORD_ERROR,
            "连接失败"
        )
        is SSLHandshakeException -> ResponseThrowable(
            e,
            SSL_ERROR,
            "证书验证失败"
        )
        is SocketTimeoutException -> ResponseThrowable(
            e,
            TIMEOUT_ERROR,
            "连接超时"
        )
        is ServerException -> ResponseThrowable(e, e.code, e.message)
        else -> {
            ResponseThrowable(
                e,
                UNKNOWN,
                "unknown ic_error" + e.message
            )
        }
    }

    class ResponseThrowable(throwable: Throwable?, val respCode: Int, val respMessage: String?) :
        Exception(throwable)

    //后端回调
    class ServerException(val code: Int, override val message: String?) : Throwable()


}